package com.haidechizi.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;

/**
 *
 */
public class _40_组合总和II {

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Set<List<Integer>> result = new HashSet<>();
        Stack<Integer> stack = new Stack<>();
        Arrays.sort(candidates);
        generateSum(0, candidates, target, result, stack);
        List<List<Integer>> lists = new ArrayList<>();
        lists.addAll(result);
        return lists;
    }

    public void generateSum(int i, int[] candidates, int target, Set<List<Integer>> result, Stack<Integer> stack) {
        if (i >= candidates.length) {
            return;
        }

        // 放入第ige
        stack.push(candidates[i]);
        if(addResult(result, stack, target) ){
            generateSum(i + 1, candidates, target, result, stack);
        }
        stack.pop();
        generateSum(i + 1, candidates, target, result, stack);
    }

    public boolean addResult(Set<List<Integer>> result, Stack<Integer> stack, int target) {
        List<Integer> list = new ArrayList<>();
        int sum = 0;
        for (Integer value : stack) {
            sum += value;
            list.add(value);
        }
        if (sum == target) {
            result.add(list);
            return false;
        }
        if (sum > target) {
            return false;
        }
        return true;
    }
}
